package com.ceprei.gui.shiro;

import com.ceprei.domain.modules.sys.entity.User;
import com.ceprei.gui.shiro.jwt.JwtToken;
import com.ceprei.gui.shiro.jwt.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;

/**
 * @author zhou minghao
 * @date 2024/11/28
 * @description
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private TokenService tokenService;

    /**
     * 从数据库获取用户信息进行认证
     * @param auth the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        log.debug("===============Shiro身份认证开始============doGetAuthenticationInfo==========");
        Object token = auth.getPrincipal();
        if(ObjectUtils.isEmpty(token)){
            throw new ExpiredCredentialsException("凭证为空！");
        }

        // 校验token有效性
        User user = tokenService.verificationToken((String) token);
        //
        return new SimpleAuthenticationInfo(user, token, getName());


    }
    
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(new HashSet<>());
        return info;
    }

   

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
